// pages/cashier_table_add/cashier_table_add.js
let assistObj = {},
    flagKey = ''

// 业务收支、员工收支模块参数信息
let entityParam = {}

let today = wx.$util.formatDate(new Date(), 'yyyy-MM-dd')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    auth: {},

    isEdit: false,
    rowId: null,
    detlData: null,
    assistDetlData: null,
    reqTotal: 0,

    fieldList: [
      { field_id: 'date', label: '发生日期', type: 'datetime', is_null: false, defaultValue: wx.$util.formatDate(new Date(), 'yyyy-MM-dd'), plc: '', length: '', },
      { field_id: 'mark', label: '摘要', type: 'splc', is_null: false, plc: '请填写摘要', },
      { field_id: 'debit_amount', label: '收入', type: 'num', precision: 2, nonNeg: true, is_null: true, plc: '请输入金额', },
      { field_id: 'credit_amount', label: '支出', type: 'num', precision: 2, nonNeg: true, is_null: true, plc: '请输入金额', },
      { field_id: 'account_id', label: '账号', type: 'picklist', is_null: false, optionList: [], optionId: 'number', optionName: 'account_shortname', },
      { field_id: 'account_period', label: '会计期', type: 'picklist', is_null: false, optionList: [], optionId: 'account_period', optionName: 'account_period', },
      { field_id: 'target_account_id', label: '会计科目', type: 'picklist', is_null: false, addBtn: false, optionList: [], optionId: 'account_id', optionName: 'account_name', isAssist: true, },
      { field_id: 'attached', label: '附件', type: 'picture', is_null: true, },
    ],
    validFlag: false,             // 验证标识
    validData: {},                // 验证表单项
    formData: {
      date: '',
      mark: '',
      cashier_type: '', // 出纳类型选择
      debit_amount: '',
      credit_amount: '',
      account_id: '',
      account: '',
      account_period: '',
      target_account_id: '',
      target_account_name: '',
      attached: '',
      // assist_account_json: '',
      // quantity: '',
      // quantity_unit_price: '',
    },
    assistFieldList: [],
    assistFormData: {},
    assistValidData: {},

    fieldVal: {
      target_account_id: '',
    },
    disObj: {},

    targetAccountId: '',

    // 摘要相关
    selectFlag0: false,
    optList0: [
      { id: 'everyday', name: '日常收支', rlatKey: 'selectFlag1', },
      { id: 'business', name: '业务收支', rlatKey: 'selectFlag2', },
      { id: 'employee', name: '员工收支', rlatKey: 'selectFlag3', },
    ],
    val0: '',
    // 各类型收支列表，日常/业务/员工收支
    selectFlag1: false,
    optList1: [],
    selectFlag2: false,
    optList2: [],
    selectFlag3: false,
    optList3: [],
    val1: '',
    // 订单选择
    selectFlag4: false,
    optList4: [],
    page: 1,
    listTotal: 0,
    pageLimit: 10,
    list4Args: [],
    optCols: [
      { field_id: 'Order_No', label: '订单编号', },
      { field_id: 'Order_client_ID', label: '往来单位', type: 'reference1' },
      { field_id: 'Order_date', label: '签订日期', colType: 'sub', },
      { field_id: 'Order_amount', label: '合同金额', colType: 'sub', },
      { field_id: 'Order_amount_processed', label: '已收支金额', colType: 'sub', },
      { field_id: 'Order_amount_unprocessed', label: '未收支金额', colType: 'sub', },
      { field_id: 'salesman', label: '业务员', type: 'reference1', colType: 'sub', },
      { field_id: 'abstract', label: '摘要', type: 'textarea', colType: 'sub', },
    ],
    val2: '',
    isFocus: false,
    autoFocus: false,
    // 摘要 mark
    val3: '',
    debit_amount: '',
    credit_amount: '',
    // 无订单往来
    selectFlag5: false,
    optList5: [],


    // 辅助核算设置
    assistOptList: [],

    // 附件
    uploadImg: [],

    // diy模块收付款传入参数
    diyParams: {},
    // 获取科目列表
    accountantCourse: [],
  },

  // 双向绑定 报警告处理
  inputIpt(e) {},
  focusIpt(e) {
    let { val0, val1, val2, detlData, } = this.data
    if(!detlData) {
      if((!val0 || !val1 || (['business', 'employee', ].includes(val0.id) && !val2))) {
        // 收起键盘
        wx.hideKeyboard()
        return
      }
    }
    this.setData({
      isFocus: true,
    })
  },
  blurIpt(e) {
    this.setData({
      isFocus: false,
    })
  },
  resetIpt(e) {
    if(this.data.diyParams.Entity) {  // diy 模块进来的
      this.setData({
        val3: '',
      })
      return
    }
    // 收起键盘
    wx.hideKeyboard()
    this.setData({
      val0: '',
      val1: '',
      val2: '',
      val3: '',
      isFocus: false,
    })
  },

  toggleFlag(e) {
    let key = e.currentTarget.dataset.key,
        { val0, val1, val2, val3, detlData, } = this.data
    if(val0 && ((val0.id !== 'everyday' && val2) || (val0.id === 'everyday' && val1)) || detlData) return
    // if(val1 && flagKey) key = flagKey

    this.setData({
      [key]: !this.data[key],
    })
  },
  async select(e) {
    let key = e.currentTarget.dataset.key,
        { fieldVal, } = this.data,
        disObj = {
          debit_amount: false,
          credit_amount: false,
        }

    if(key === '0') {
      // flagKey = e.detail.rlatKey
      let { rlatKey, } = e.detail
      this.setData({
        // [flagKey]: !this.data[flagKey],
        [rlatKey]: !this.data[rlatKey],
        val0: e.detail,
      })
      console.log(this.data.val0);

    } else if(key === '1') {  // 日常收支
      fieldVal.target_account_id = e.detail['huijikemu']
      if(e.detail.payment_type === '收') disObj.credit_amount = true
      else if(e.detail.payment_type === '支') disObj.debit_amount = true
      this.setData({
        fieldVal,
        disObj,
        val1: e.detail,
        val3: e.detail.abstract_type + '-',
        autoFocus: true,
      })
    } else if(key === '2') {  // 业务收支
      let { target_account_id, IncomeOrExpenditure, table_id, } = e.detail
      if(table_id === '$NULL$') { // 无订单往来，特殊处理
        this.setData({
          val1: e.detail,
          selectFlag5: !this.data.selectFlag5,
        })
        return
      }
      if(!entityParam[table_id]) await this.getEntityParam(table_id)
      fieldVal.target_account_id = target_account_id

      this.setData({
        fieldVal,
        val1: e.detail,
        selectFlag4: !this.data.selectFlag4,
      })
      this.data.page = 1
      let args = [table_id, IncomeOrExpenditure, entityParam[table_id].is_verify]
      this.data.list4Args = args
      this.getOption4List(...args)

      console.log(this.data.val1);

    } else if(key === '3') {  // 员工收支
      let { target_account_id, IncomeOrExpenditure, table_id, } = e.detail
      if(!entityParam[table_id]) await this.getEntityParam(table_id)
      fieldVal.target_account_id = target_account_id

      this.setData({
        fieldVal,
        val1: e.detail,
        selectFlag4: !this.data.selectFlag4,
      })
      this.data.page = 1
      let args = [table_id, IncomeOrExpenditure, entityParam[table_id].is_verify]
      this.data.list4Args = args
      this.getOption4List(...args)
    } else if(key === '4') {  // 订单
      let selItem = e.detail.val,
          name = selItem['Order_client_ID;value']

      if(!selItem.Order_client_ID) return
      let { val0, val1, } = this.data,
          { IncomeOrExpenditure, } = this.data.val1,
          obj = {
            disObj,
            val2: selItem,
            val3: `${name}${name ? '-' : ''}`,
            autoFocus: true,
            debit_amount: '',
            credit_amount: '',
          }
      if(IncomeOrExpenditure === '收') {
        disObj.credit_amount = true
        obj.debit_amount = { debit_amount: selItem.Order_amount_unprocessed, }
      } else if(IncomeOrExpenditure === '支') {
        disObj.debit_amount = true
        obj.credit_amount = { credit_amount: selItem.Order_amount_unprocessed, }
      }
      if(val0 && ['business', 'employee'].includes(val0.id)) {  // 业务收支 员工收支
        this.getCustomerAcct(val1.target_account_id, selItem.Order_client_ID)
      }

      this.setData(obj)
    } else if(key === '5') {  // 无订单往来
      let selItem = e.detail,
          name = selItem.name
      this.setData({
        disObj,
        val2: selItem,
        val3: `${name}${name ? '-' : ''}`,
        autoFocus: true,
      })
    }
  },
  back(e) {
    let { val0, val1, val2, } = this.data,
        idx = e.currentTarget.dataset.key,
        key = ''

    if(['1', '2', '3', ].includes(idx)) key = 'selectFlag0'
    else if(idx === '4' && val0.id === 'business') key = 'selectFlag2'
    else if(idx === '4' && val0.id === 'employee') key = 'selectFlag3'
    else if(idx === '5') key = 'selectFlag2'
    if(!key) return
    this.setData({
      [key]: !this.data[key],
    })
  },
  changeIpt(e) {
    let { field, val, } = e.detail,
        { field_id, optionList, optionId, optionName, } = field,
        { formData, isEdit, } = this.data

    if(field_id === 'target_account_id') this.dealTargetAcct(field, val, formData[field_id])

    if(isEdit && ['credit_amount', 'debit_amount'].includes(field_id)) {
      let key = field_id === 'credit_amount' ? 'debit_amount' : 'credit_amount'
      if(formData[key] && val) {  // 编辑时，收入、支出只能其中一个有值
        this.setData({
          [key]: { [key]: 0, },
        })
      }
    }

    if(['account_id', 'target_account_id',].includes(field_id)) {
      let selItem = null
      optionList.some(opt => {
        if(opt[optionId] === val) {
          selItem = opt
          return true
        }
      })
      let key = field_id === 'account_id' ? 'account' : 'target_account_name'

      this.setData({
        [`formData.${key}`]: selItem ? selItem[optionName] : '',
      })
    }

    if(formData[field_id] !== undefined) {
      this.setData({
        [`formData.${field_id}`]: val,
      })
    }
  },
  changeIptAssist(e) {
    let { field, val, } = e.detail,
        { field_id, type, optionList, optionId, optionName, } = field,
        { assistFormData, } = this.data
    assistFormData[field_id] = val

    if(type === 'picklist') {
      if(val) val = Number(val)
      let selArr = optionList.filter(opt => opt[optionId] === val),
          selItem = selArr.length ? selArr[0] : null
      if(selItem) {
        selItem = {
          id: selItem[optionId],
          name: `${selItem[optionId]} ${selItem[optionName]}`,
          type: field.assist_account_json,
        }
      }
      assistFormData[field_id] = selItem || ''
    }
    this.data.assistFormData = assistFormData
  },
  // 会计科目处理
  dealTargetAcct(field, val, oldVal, dfltValObj) {
    let { fieldList, assistFieldList, formData, auth, } = this.data,
        { optionList, optionId, } = field,
        { fieldSee, fieldEdit, fieldAppend, } = auth,
        hasRight = fieldSee.includes('target_account_id') && fieldEdit.includes('target_account_id') && fieldAppend.includes('target_account_id'),
        selItem = null
    if(val && val === oldVal) return
    if(!hasRight) return
    optionList.forEach(opt => {
      if(opt[optionId] === val) {
        selItem = opt
        return
      }
    })
    if(!selItem) return
    if(selItem.is_assist_account) { // 需要辅助核算
      console.log('需要辅助核算的');
      let rowIds = selItem.assist_account_json.split(','),
          proArr = [],
          arr = []
      rowIds.forEach(rid => {
        // 获取辅助核算要填的几个框的选项
        if(assistObj[rid]) {
          arr.push(assistObj[rid])
          let { table_id, } = assistObj[rid]
          proArr.push(this.getOptionList(0, '', 3, 'DynamicQuery/query_dynamic_v3', { limit: 0, oby: `${table_id}.row_id desc`, page: 1, table_id: table_id, }))
        }
      })
      Promise.all(proArr).then(res => {
        assistFieldList = selItem.is_quantity_account ? [
          { field_id: 'quantity', label: '数量', type: 'num', precision: 4, is_null: true, plc: '请输入数量', },
          { field_id: 'quantity_unit_price', label: '单价', type: 'num', precision: 4, is_null: true, plc: '请输入单价', },
        ] : []
        let obj = selItem.is_quantity_account ? { quantity: '', quantity_unit_price: '', } : {}
        res.forEach((rows, r) => {
          let fieldItem =
          assistFieldList.push({
            field_id: `json_${r}`,
            label: arr[r].assist_account,
            type: 'picklist',
            is_null: false,
            optionList: rows,
            optionId: 'row_id',
            optionName: arr[r].field_id,
            assist_account_json: rowIds[r],

            rid: rowIds[r],
          })
          obj[`json_${r}`] = ''
        })

        // 设业务收支传入的默认辅助核算值
        if(dfltValObj) {
          assistFieldList.forEach(item => {
            let fieldId = item.field_id
            if(item.rid !== undefined) fieldId = item.rid
            let defaultValue = dfltValObj[fieldId]
            if(!['', null, undefined].includes(defaultValue)) item.defaultValue = defaultValue
          })
        }

        this.setData({
          assistFieldList,
        })
        this.data.assistFormData = obj

        this.setDetlData()
      })
    } else {  // 不需要辅助核算
      if(!assistFieldList.length) return
      this.setData({
        assistFieldList: [],
        assistFormData: {},
        assistValidData: {},
      })
    }
  },
  // 记录验证表单项
  validIpt(e) {
    let { validData, } = this.data
    this.data.validData = {
      ...validData,
      ...e.detail,
    }
  },
  validIptAssist(e) {
    let { assistValidData, } = this.data
    this.data.assistValidData = {
      ...assistValidData,
      ...e.detail,
    }
  },
  // 保存/保存并新增
  saveData(e) {
    let { auth, isEdit, } = this.data
    if(isEdit) {
      this.onEdit(e)
      return
    }
    if(!auth.tableAppend) {
      wx.$toast('抱歉，您没有权限新增该模块数据').then(() => {
        wx.navigateBack({
          delta: 1,
        })
      })
      return
    }

    let { reset, } = e.currentTarget.dataset
    this.data.validData = {}
    this.setData({
      validFlag: !this.data.validFlag,
    })

    let { fieldList, formData, validData, val0, val1, val2, val3, assistFieldList, assistFormData, assistValidData, disObj, } = this.data;

    if(!val3 || (!val1 && !val2)) validData.mark = false
    // validData = {
    //   ...validData,
    //   account: true,
    //   cashier_type: true,
    //   target_account_name: true,
    // }
    Promise.all([wx.$validForm(fieldList, validData), wx.$validForm(assistFieldList, assistValidData)]).then(res => {
      if(res.includes(false)) {
        wx.$toast('必填项不能为空！')
        return
      }
      if(!disObj.credit_amount && !disObj.debit_amount) {
        if(formData.credit_amount !== '' && formData.debit_amount !== '') {
          wx.$toast('收入金额和支出金额只可填写一个！')
          return
        }
      } else {
        if(!disObj.credit_amount && formData.credit_amount === '') {
          wx.$toast('金额不能为空！')
          return
        } else if(!disObj.debit_amount && formData.debit_amount === '') {
          wx.$toast('金额不能为空！')
          return
        }
      }


      let post = JSON.parse(JSON.stringify(formData))
      post.cashier_type = val0.name
      post.mark = val3
      if(this.data.sort) post.sort = this.data.sort
      if(val0.id === 'business') {
        if(val1.table_id === '$NULL$') {
          post.Order_client_ID = val2.id
          post.Order_client_Name = val2.name
        } else {
          post.Order_client_ID = val2.Order_client_ID
          post.Order_client_Name = val2['Order_client_ID;value']
          post.order_row_id_list = val2.row_id
          post.order_table_id = val1.table_id
        }
      } else if(val0.id === 'employee') {
        post.Order_client_ID = val2.Order_client_ID
        post.Order_client_Name = val2['Order_client_ID;value']
        post.order_row_id_list = val2.row_id
        post.order_table_id = val1.table_id
      }
      let idArr = [],
          nameArr = [],
          typeArr = []
      Object.keys(assistFormData).forEach(key => {
        let val = assistFormData[key]
        if(key.indexOf('json_') > -1) {
          idArr.push(val.id)
          nameArr.push(val.name)
          typeArr.push(val.type)
        } else if(val !== '') {
          post[key] = val
        }
      })
      if(idArr.length) {
        let obj = {
          id: idArr.join(','),
          name: nameArr.join(','),
          type: typeArr.join(','),
        }
        post.assist_account_json = JSON.stringify(obj)
      }

      wx.showLoading({ mask: true, })
      this.saveFormData(post).then(res => {
        wx.$toast('保存成功！', 2000).then(() => {
          if(reset) { // 保存并新增
            wx.redirectTo({
              url: '../cashier_table_add/cashier_table_add?entity=all_cashier',
            })
          } else {  // 保存
            let pages = getCurrentPages(), // 获取页面栈
                beforePage = pages[pages.length - 2]  //前一个页面
            if(beforePage.getFirstPage) beforePage.getFirstPage()
            wx.navigateBack({
              delta: 1,
            })
          }
        })
      })
    })
  },
  // 编辑 保存/保存并新增
  onEdit(e) {
    let { auth, } = this.data
    if(!auth.tableEdit) {
      wx.$toast('抱歉，您没有权限编辑该模块数据').then(() => {
        wx.navigateBack({
          delta: 1,
        })
      })
      return
    }

    let { reset, } = e.currentTarget.dataset
    this.data.validData = {}
    this.setData({
      validFlag: !this.data.validFlag,
    })

    let { detlData, fieldList, formData, validData, val3, assistFieldList, assistFormData, assistValidData, } = this.data
    if(!val3) validData.mark = false
    Promise.all([wx.$validForm(fieldList, validData), wx.$validForm(assistFieldList, assistValidData)]).then(res => {
      if(res.includes(false)) {
        wx.$toast('必填项不能为空！')
        return
      }
      if(formData.credit_amount === '' && formData.debit_amount === '') {
        wx.$toast('收入金额和支出金额必须填写一个！')
        return
      }

      let post = JSON.parse(JSON.stringify(formData))
      post.cashier_type = detlData.cashier_type
      post.mark = val3
      post.sort = detlData.sort
      post.row_id = detlData.row_id
      let idArr = [],
          nameArr = [],
          typeArr = []
      Object.keys(assistFormData).forEach(key => {
        let val = assistFormData[key]
        if(key.indexOf('json_') > -1) {
          idArr.push(val.id)
          nameArr.push(val.name)
          typeArr.push(val.type)
        } else if(val !== '') {
          post[key] = val
        }
      })
      if(idArr.length) {
        let obj = {
          id: idArr.join(','),
          name: nameArr.join(','),
          type: typeArr.join(','),
        }
        post.assist_account_json = JSON.stringify(obj)
      }

      wx.showLoading({ mask: true, })
      this.saveFormData(post).then(res => {
        wx.$toast('保存成功', 2000).then(() => {
          if(reset) { // 保存成功
            wx.redirectTo({
              url: '../cashier_table_add/cashier_table_add?entity=all_cashier',
            })
          } else {
            let pages = getCurrentPages(), // 获取页面栈
                beforePage = pages[pages.length - 2]  //前一个页面

            if(beforePage.refreshData) beforePage.refreshData()

            wx.navigateBack({
              delta: 1,
            })
          }
        })
      })
    })
  },

  // 订单引用查询
  searchCols(e) {
    this.data.page = 1
    let args = this.data.list4Args
    this.getOption4List(...args, e.detail)
  },
  prevData(e) {
    this.data.page = this.data.page - 1
    let args = this.data.list4Args
    this.getOption4List(...args, e.detail)
  },
  nextData(e) {
    this.data.page = this.data.page + 1
    let args = this.data.list4Args
    this.getOption4List(...args, e.detail)
  },

  // select/selectCols 引用新增
  toAddList1(e) {
    this.data.addListKey = 'optList1'
    wx.navigateTo({
      url: '/DIYPages/general_edit/general_edit?entity=account_comparison',
    })
  },
  toAddList4(e) {
    this.data.addListKey = 'optList4'
    wx.navigateTo({
      url: '/DIYPages/general_edit/general_edit?entity=assembly_order',
    })
  },

  // 接口
  ready() {
    // 获取账号、会计期、会计科目 选项列表
    let p0 = this.getOptionList(0, 'account_id', 3, 'DynamicQuery/query_dynamic', { limit: 0, oby: 'account_id', page: 0, table_id: 'all_cashier_account', }),
        p1 = this.getOptionList(0, 'account_period', 3, 'Account/query_all_account_period', { account_state: '处理', }),
        p2 = this.getOptionList(0, 'target_account_id', 3, 'Account/query_account_last', { page: 1, limit: 0, oby: 'account_id', })

    Promise.all([p0, p1, p2]).then(res => {
      let fieldList = this.data.fieldList,
          obj = {}
      Object.values(res[2]).forEach(arr => {
        arr.forEach(item => item.account_name = `${item.account_id} ${item.account_name}`)
      })
      res.forEach((item, i) => {
        obj = { ...obj, ...item, }
      })
      fieldList.forEach(item => {
        let key = item.field_id
        if(obj[key]) {
          item.optionList = obj[key]
          if(key === 'account_period' && obj[key].length) {
            item.defaultValue = obj[key][0].account_period
          }
        }
      })

      this.setData({
        fieldList,
      })
      this.setDetlData()
    })

    // 获取 日常收支、业务收支、员工收支 选项列表
    let p3 = this.getOptionList(0, '', 3, 'DynamicQuery/query_dynamic_v1', { limit: 0, oby: 'account_comparison.row_id desc', page: 1, table_id: 'account_comparison', }),
        p4 = this.getOptionList(0, '', 1, 'AllCashierEntity/select_all_cashier_entity', {}),
        p5 = this.getOptionList(0, '', 1, 'AllCashierEntity/select_all_cashier_entity_approval', {}),
        // 获取无订单往来
        p6 = this.getOptionList(1, '', 3, 'Customer/select_customer', {})
    Promise.all([p3, p4, p5, p6]).then(res => {
      res[1].unshift({ table_id: '$NULL$', table_name: '无订单往来', },)
      res.forEach((rows, i) => {
        if(!i) rows.forEach(row => row.name = `${row.payment_type}-${row.abstract_type}`)
        else if(i === 1) rows.forEach(row => row.name = row.table_name)
        else if(i === 2) rows.forEach(row => row.name = row.table_name)
      })
      this.setData({
        optList1: res[0],
        optList2: res[1],
        optList3: res[2],
        optList5: res[3],
      })

      if(this.data.diyParams.Entity) this.dealFromDiy()
    })

    // 获取辅助核算设置
    this.getOptionList(0, '', 1, 'AllAssistAccount/select_all_assist_account', {}).then(rows => {
      assistObj = {}
      rows.forEach(item => assistObj[item.row_id] = item)
      this.setData({
        assistOptList: rows,
      })
      this.setDetlData()
    })
  },
  getOptionList() {
    return new Promise((resolve, reject) => {
      let [ method, key, v, url, params, ] = arguments
      let request = method ? wx.$get : wx.$post
      request(v, url, params).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        rows = rows.flat()
        resolve(key ? { [key]: rows, } : rows)
      })
    })
  },
  // 获取模块参数
  getEntityParam(entity) {
    return new Promise((resolve, reject) => {
      wx.$post(3, 'Entity_param/query_entity_param', { table_id: entity, }).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        if(rows.length) {
          entityParam[entity] = rows[0]
          resolve(entityParam[entity])
        }
      })
    })
  },
  getOption4List(tableid, paytype, ischeck, query) {
    let { page, pageLimit, optCols, } = this.data,
        filters = [],
        post = {
          page,
          limit: pageLimit,
          oby: `${tableid}.Order_date,${tableid}.Order_No`,
          table_id: tableid,
          // SearchWhere: {
          //   type: 'and',
          //   filters: [],
          // },
        }
    if(paytype !== '收支') {
      filters.push({
        CompareWith: `isnull(${tableid}.Order_amount,0)-isnull(${tableid}.Order_amount_processed,0)`,
        Operator: '>',
        CompareValue: '0',
        or: 0,
      })
    }
    if(ischeck) {
      filters.push({
        CompareWith: `${tableid}.is_Checked`,
        Operator: '=',
        CompareValue: 1,
        or: 0,
      })
    }
    if(filters.length) {
      post.SearchWhere = {
        type: 'and',
        filters: filters,
      }
    }
    if(query) {
      let queryArr = []
      optCols.forEach(col => {
        let key = col.field_id
        if(key !== 'salesman') {
          queryArr.push({
            CompareValue: query,
            CompareWith: `${tableid}.${key}`,
            Operator: 'like',
            or: 1,
          })
        }
      })
      if(post.SearchWhere) {
        post.SearchWhere.children = [
          {
            type: 'and',
            filters: queryArr,
          },
        ]
      } else {
        post.SearchWhere = {
          type: 'and',
          filters: queryArr,
        }
      }
    }

    return new Promise((resolve, reject) => {
      wx.$post(3, 'DynamicQuery/query_dynamic_v3', post).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        this.setData({
          optList4: rows,
          listTotal: res.data.total,
        })
        resolve()
      })
    })
  },
  saveFormData(post) {
    let url = 'Cashier/create_all_cashier'
    if(this.data.isEdit) url = 'Cashier/alter_all_cashier'
    return new Promise((resolve, reject) => {
      wx.$post(3, url, post).then(res => {
        if(res.errcode !== 0) return
        resolve()
      })
    })
  },

  // diy模块 收付款 跳转过来的处理逻辑
  // pages/general_entity/relate_cashier.html
  async dealFromDiy() {
    let { IncomeType, Rowids, Entity, AcId, } = this.data.diyParams
    let entityParam = await this.getEntityParam(Entity)
    if(entityParam) {
      this.data.diyParams = {
        ...this.data.diyParams,
        entityParam,
      }
    }
    this.getBusinessList(Entity, Rowids)
  },
  // 获取业务单
  getBusinessList(Entity, Rowids) {
    let post = {
      page: 1,
      limit: 0,
      oby: `${Entity}.row_id desc`,
      table_id: Entity,
      SearchWhere: {
        type: 'and',
        filters: [],
      },
    }

    let filters = [
      {
        CompareWith: `${Entity}.row_id`,
        Operator: 'in',
        CompareValue: Rowids,
        or: 1,
      }
    ]
    post.SearchWhere.filters = filters

    wx.$post(3, 'DynamicQuery/query_dynamic_v3', post).then(res => {
      if(res.errcode !== 0) return
      let rows = res.data.row,
          entityParam = this.data.diyParams.entityParam,
          msg = ''
      rows.some(item => {
        if(!item.Order_client_ID) {
          msg = '所选订单中存在订单未选择客户！'
          return true
        }
        if((!entityParam || entityParam.is_verify) && !item.is_Checked) {
          msg = '所选订单中存在订单未审核！'
          return true
        }
        if(Number(item.Order_amount) - Number(item.Order_amount_processed) <= 0) {
          msg = '所选订单中存在订单可处理金额为0！'
          return true
        }
      })
      if(msg) {
        wx.showModal({
          // title: '',
          content: msg,
          success: (res) => {
            wx.navigateBack({
              delta: 1,
            })
          },
        })
        return
      }

      // 填充默认数据
      if(rows.length && Entity !== '$NULL$') {
        let row = rows[0],
            { optList0, optList2, diyParams, disObj, } = this.data,
            val0 = optList0.filter(opt => opt.id === 'business')[0] || '',
            val1 = optList2.filter(opt => opt.table_id === Entity)[0] || '',
            obj = {
              val0,
              val1,
              disObj: {
                ...disObj,
                debit_amount: false,
                credit_amount: false,
                // target_account_id: true,
              }
            }
        if(val1) {
          obj.val2 = {
            row_id: row.row_id,
            Order_client_ID: row.Order_client_ID,
            ['Order_client_ID;value']: row['Order_client_ID;value'],
            Order_amount_unprocessed: row.Order_amount_unprocessed,
          }
          obj.val3 = `${row['Order_client_ID;value']}-`

          let { IncomeOrExpenditure, } = val1
          if(IncomeOrExpenditure === '收') {
            obj.disObj.credit_amount = true
            obj.debit_amount = { debit_amount: row.Order_amount_unprocessed, }
          } else if(IncomeOrExpenditure === '支') {
            obj.disObj.debit_amount = true
            obj.credit_amount = { credit_amount: row.Order_amount_unprocessed, }
          }

          // let subRows = this.data.accountantCourse,
          //     isExist = subRows.filter(item => item.id == (diyParams.AcId + row['Order_client_ID'])).length
          // obj.fieldVal = {
          //   target_account_id: isExist ? (diyParams.AcId + row['Order_client_ID']) : diyParams.AcId,
          // }
          // 221110 改用getCustomerAcct，增加判断
          this.getCustomerAcct(diyParams.AcId, row['Order_client_ID'])

        }

        this.setData(obj)
      }
    })
  },
  // 获取会计科目
  getSubject() {
    return new Promise((resolve, reject) => {
      wx.$get(3, 'Account/select_account', {}).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        this.data.accountantCourse = rows
        resolve(rows)
      })
    })
  },
  // 获取客户账户
  getCustomerAcct(accountid, clientid) {
    let post = {
      ParentAccountId: accountid,
      CustomerId: clientid,
    }
    return new Promise((resolve, reject) => {
      wx.$post(3, 'Account/GetAllAccountByCustomer', post).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row,
            { auth, val1, val2, accountantCourse, } = this.data,
            subRows = accountantCourse,
            isExist = subRows.filter(item => item.id == (accountid + clientid)).length,
            target_account_id = ''
        if(rows.length) {
          target_account_id = rows[0] && rows[0].AccountId
        } else {
          target_account_id = isExist ? (accountid + clientid) : accountid
        }
        if(target_account_id) {
          this.data.formData.target_account_id = target_account_id
          this.setData({
            fieldVal: { target_account_id, },
          })
        }

        let { fieldEdit, fieldSee, } = auth,
            isAssist = entityParam[val1.table_id].is_assist_account
        if(fieldEdit && fieldEdit.includes('target_account_id') && fieldSee.includes('target_account_id')) {  // 有权限
          if(isAssist && val2) {
            let json = ''
            try {
              json = JSON.parse(val2.assist_account_json)
            } catch(error) {}
            if(json) {
              let typeArr = json.type.toString().split(','),
                  idArr = json.id.toString().split(','),
                  valObj = {},
                  quantity = val2.quantity || 0,
                  quantity_unit_price = (val2.quantity_unit_price || 0) * quantity,
                  fieldItem = this.data.fieldList.filter(item => item.field_id === 'target_account_id')[0]
              typeArr.forEach((item, i) => {
                valObj[item] = idArr[i]
              })
              valObj.quantity = quantity
              valObj.quantity_unit_price = quantity_unit_price

              this.dealTargetAcct(fieldItem, target_account_id, '', valObj)
            }
          }
        }

        resolve()
      })
    })
  },

  // 获取数据
  getDetlData() {
    let { rowId,} = this.data,
        post = {
          page: 1,
          limit: 1,
          oby: 'sort',
          SearchWhere: {
            type: 'and',
            filters: [ { CompareValue: rowId, CompareWith: 'row_id', Operator: '=', or: 0, }, ],
            children: [],
          },
        }
    wx.$post(3, 'Cashier/query_all_cashier', post).then(res => {
      if(res.errcode !== 0) return
      let row = res.data.row[0]
      if(row.row_id === 0) {
        wx.$toast('该记录不存在').then(() => {
          wx.navigateBack({
            delta: 1,
          })
        })
        return
      }
      this.data.detlData = row
      this.setDetlData()
    })
  },
  setDetlData() {
    if(!this.data.isEdit) return
    this.data.reqTotal++
    let { reqTotal, detlData, fieldVal, assistFieldList, } = this.data
    if(reqTotal === 3) {
      let { date, target_account_id, debit_amount, credit_amount, mark, assist_account_json, quantity_unit_price, quantity, } = detlData,
          obj = {}
      detlData.date = (date || '').slice(0, 10)
      fieldVal.target_account_id = target_account_id

      if(quantity_unit_price !== null) obj.quantity_unit_price = quantity_unit_price
      if(quantity !== null) obj.quantity = quantity
      this.data.assistDetlData = obj
      this.setData({
        detlData,
        fieldVal,
        debit_amount: { debit_amount, },
        credit_amount: { credit_amount, },
        val3: mark,
      })
    } else if(reqTotal === 4) {
      let { assist_account_json, } = detlData,
          { assistDetlData, } = this.data
      if(assist_account_json) {
        assist_account_json = JSON.parse(assist_account_json)
        let ids = assist_account_json.id.split(','),
            types = assist_account_json.type.split(','),
            obj = {}
        types.forEach((type, t) => {
          obj[type] = ids[t]
        })
        assistFieldList.forEach(field => {
          if(field.rid !== undefined && obj[field.rid] !== undefined) {
            assistDetlData[field.field_id] = obj[field.rid]
          }
        })
        this.setData({
          assistDetlData,
        })
      }
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();
    assistObj = {}
    entityParam = {}

    // 221114 出纳表查看跳转 传入
    let { status, rid, } = options,
        isEdit = status === 'edit'
    if(isEdit) {
      this.setData({
        isEdit,
        rowId: rid,
      })
    }

    let { entity, acid, income, rids, sort, } = options,
        auth = await wx.$getAuth('all_cashier')
    this.data.auth = auth

    // 221114 出纳表插入跳转 传入
    if(sort) this.data.sort = sort

    if(!auth.tableAppend) {
      wx.$toast('抱歉，您没有权限新增该模块数据').then(() => {
        wx.navigateBack({
          delta: 1,
        })
      })
      return
    }
    // 判断是否有权限新增附件
    if(!auth.fieldAppend.includes('attached')) {
      let { disObj, } = this.data
      disObj.attached = true
      this.setData({
        disObj,
      })
    }
    if(entity !== 'all_cashier') {  // 从自定义模块的 收付款 按钮链接进入的
      console.log(options);
      this.data.diyParams = {
        IncomeType: income,
        Rowids: rids,        // 所选行id
        Entity: entity,      // 模块id
        AcId: acid,          // 科目id
      }
    }

    await this.getSubject()
    this.ready()

    // 221114 出纳表查看跳转 传入
    if(status === 'edit') {
      this.getDetlData()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let { addListKey, } = this.data
    if(addListKey === 'optList1') {
      this.getOptionList(0, '', 3, 'DynamicQuery/query_dynamic_v1', { limit: 0, oby: 'account_comparison.row_id desc', page: 1, table_id: 'account_comparison', }).then(rows => {
        rows.forEach(row => row.name = `${row.payment_type}-${row.abstract_type}`)
        this.setData({
          optList1: rows,
        })
      })
    } else if(addListKey === 'optList4') {
      // this.searchCols({ detail: '', })
      let compThis = this.selectComponent('#orderSel')
      compThis.setData({
        searchVal: '',
      })
      compThis.searchIpt({ detail: {value: '', }, })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
